<template>
    <view>
        <view class="upload">
            <block v-for="(upload,index) in uploads" :key="index">
                <view class="uplode-file">
                    <image mode="aspectFill" v-if="types == 'image'&&upload.filetype=='jpg'" class="uploade-img"
                        :src="upload.url" :data-src="upload.url" @tap="previewImage(upload)"></image>
                    <image mode="aspectFill" v-if="types == 'image'" class="clear-one-icon"
                        src="@/static/img/publish/img_close.png" @tap="delImage(index)">
                    </image>
                    <image mode="aspectFill"
                        v-if="upload.filetype=='docx'||upload.filetype=='doc'||upload.filetype=='xls'
                    ||upload.filetype=='xlsx'||upload.filetype=='ppt'||upload.filetype=='pptx'||upload.filetype=='pdf'||upload.filetype=='PDF'"
                        class="uploade-img" src="@/static/img/publish/wd.png" @tap="previewImage(upload)"></image>
                    <video v-if="types == 'video'" autoplay="true" direction="90" loop="true" :src="upload.url" controls
                        style="position: relative;">
                        <cover-image v-if="types == 'video'" class="clear-one-icon"
                            src="@/static/img/publish/img_close.png" @tap="delImage(index)">
                        </cover-image>
                    </video>
                </view>
            </block>
            <view class="add-img uplode-file cc" v-if="uploads.length < uploadCount&&types=='image'"
                @tap="chooseUploads">
                <text class='cuIcon-add link-color' style="font-size: 40px;"></text>
            </view>
            <view class="add-img uplode-file dd" @tap="chooseUploads" v-if="uploads.length!=1&&types=='video'">
                <text class='cuIcon-add link-color' style="font-size: 40px;"></text>
            </view>
            <u-toast ref="uToast" />
        </view>
    </view>
</template>

<script>
    export default {
        props: {
            types: {
                type: String,
                default: 'image'
            },
            dataList: {
                type: Array,
                default: function () {
                    return []
                }
            },
            clearIcon: {
                type: String,
                default: 'http://img1.imgtn.bdimg.com/it/u=451604666,2295832001&fm=26&gp=0.jpg'
            },
            uploadIcon: {
                type: String,
                default: ''
            },
            uploadUrl: {
                type: String,
                default: ''
            },
            deleteUrl: {
                type: String,
                default: ''
            },
            uploadCount: {
                type: Number,
                default: 1
            },
            //上传图片大小 默认3M
            upload_max: {
                type: Number,
                default: 30
            }
        },
        data() {
            return {
                isFinsel: true,
                //上传的图片地址
                uploadImages: [],
                //展示的图片地址
                uploads: [],
                // 超出限制数组
                exceeded_list: [],
            }
        },
        watch: {
            dataList: {
                handler(val) {
                    this.uploads = val;
                },
                immediate: true
            }
        },
        methods: {
            // 下载临时储存 temporary 临时 local 永久
            udownload(url, type = 'temporary') {
                let that = this;
                return new Promise((resolve, reject) => {
                    uni.downloadFile({
                        url,
                        success: ({ statusCode, tempFilePath }) => {
                            if (statusCode === 200) {
                                if (type == 'local') {
                                    uni.saveFile({
                                        tempFilePath,
                                        success: ({ savedFilePath }) => that.onCommit(resolve(savedFilePath)),
                                        fail: () => that.errorHandler('下载失败', reject)
                                    });
                                } else {
                                    that.onCommit(resolve(tempFilePath));
                                }
                            }
                        },
                        fail: () => that.errorHandler('下载失败', reject)
                    });
                });
            },
            onCommit(resolve) {
                return resolve;
            },
            // 打开文件
            uopen(filePath) {
                let system = uni.getSystemInfoSync().platform;
                if (system == 'ios') {
                    filePath = encodeURI(filePath);
                }
                uni.openDocument({
                    showMenu: true,
                    filePath,
                    success: res => {
                        console.log('打开文档成功');
                    },
                    fail: res1 => {
                        uni.getImageInfo({
                            src: filePath,
                            success: imgInfo => {
                                uni.previewImage({
                                    current: filePath,
                                    urls: [filePath]
                                });
                            },
                            fail: err => {
                                uni.showToast({
                                    title: '不支持该格式',
                                    icon: 'none'
                                });
                                return;
                            }
                        });
                    }
                });
            },
            previewImage(e) {
                if (e.filetype == 'docx' || e.filetype == 'doc' || e.filetype == 'xls' ||
                    e.filetype == 'xlsx' || e.filetype == 'ppt' || e.filetype == 'pptx'
                    || e.filetype == 'pdf' || e.filetype == 'PDF') {
                    uni.showLoading({
                        title: '下载中...',
                        mask: true
                    });
                    this.udownload(e.url, 'temporary')
                        .then(path => {
                            this.$refs.uToast.show({
                                title: path,
                                type: 'warning'
                            })
                            uni.hideLoading();
                            this.uopen(path);
                        })
                        .catch(() => {
                            uni.hideLoading();
                            uni.showToast({
                                title: '下载失败',
                                icon: 'none'
                            });
                        });
                } else {

                    var arr = []
                    arr.push(e.url)
                    // var current = e.target.dataset.src
                    uni.previewImage({
                        current: arr[0],
                        urls: arr,
                        longPressActions: {
                            itemList: ['发送给朋友', '保存图片', '收藏'],
                            success: function (data) {
                                console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
                            },
                            fail: function (err) {
                                console.log(err.errMsg);
                            }
                        }
                    });
                }
            },
            chooseUploads() {
                var t = this

                if (t.isFinsel) {
                    uni.showActionSheet({
                        title: "选择上传类型",
                        itemList: ['图片', '视频'],
                        success: (res) => {
                            console.log(res)

                            if (res.tapIndex == 1) {
                                // t.types = 'video'
                                t.$emit('typesel', 'video')
                                uni.chooseVideo({
                                    sourceType: ['camera', 'album'],
                                    success: (res) => {
                                        // t.isFinsel = false
                                        if (Math.ceil(res.size / 1024) < t.upload_max * 1024) {
                                            uni.uploadFile({
                                                url: t.$cfg.uploadurl, //仅为示例，非真实的接口地址
                                                filePath: res.tempFilePath,
                                                name: 'file',
                                                //请求参数
                                                formData: {
                                                    folderName: t.$cfg.user().userNum
                                                },
                                                success: (uploadFileRes) => {
                                                    var obj = {
                                                        name: JSON.parse(uploadFileRes.data).result.fileName,
                                                        url: JSON.parse(uploadFileRes.data).result.fileDownloadUri,
                                                    }
                                                    t.uploads.push(obj)
                                                    t.$emit('successVideo', obj)
                                                }
                                            });
                                        } else {
                                            t.exceeded_list.push(i === 0 ? 1 : i + 1);
                                            t.$refs.uToast.show({
                                                title: `第${[...new Set(t.exceeded_list)].join(',')}张图片超出限制${t.upload_max}MB,已过滤`,
                                                type: 'warning'
                                            })
                                        }
                                    },
                                    fail: (err) => {
                                        t.$refs.uToast.show({
                                            title: '已取消',
                                            type: 'error'
                                        })
                                    }
                                });
                            } else {
                                // t.types = 'image'
                                t.$emit('typesel', 'image')
                                uni.chooseImage({
                                    count: t.uploadCount - t.uploads.length, //默认9
                                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                                    sourceType: ['album', 'camera'], //从相册选择
                                    success: (res) => {
                                        const tempFilePaths = res.tempFilePaths;
                                        t.isFinsel = false
                                        for (let i = 0; i < res.tempFiles.length; i++) {
                                            console.log(res.tempFiles[i]);
                                            if (Math.ceil(res.tempFiles[i].size / 1024) < t.upload_max * 1024) {
                                                // t.uploads.push(res.tempFiles[i].path)
                                                // t.uploadImages.push(res.tempFiles[i].path)
                                                uni.uploadFile({
                                                    url: t.$cfg.uploadurl, //仅为示例，非真实的接口地址
                                                    filePath: tempFilePaths[i],
                                                    name: 'file',
                                                    formData: {
                                                        folderName: t.$cfg.user().userNum
                                                    },
                                                    success: (uploadFileRes) => {
                                                        console.log(JSON.parse(uploadFileRes.data));
                                                        var obj = {
                                                            name: JSON.parse(uploadFileRes.data).result.fileName,
                                                            url: JSON.parse(uploadFileRes.data).result.fileDownloadUri,
                                                        }
                                                        t.uploads.push(obj)
                                                        t.uploadImages.push(obj)
                                                        // t.uploads.push(JSON.parse(uploadFileRes.data).result.fileDownloadUri)
                                                        // t.uploadImages.push(JSON.parse(uploadFileRes.data).result.fileDownloadUri)
                                                        t.$emit('successImage', obj)
                                                    },
                                                    fail: (err) => {
                                                        t.$refs.uToast.show({
                                                            title: JSON.stringify(err),
                                                            type: 'error'
                                                        })

                                                    }
                                                });
                                            } else {
                                                t.exceeded_list.push(i === 0 ? 1 : i + 1);
                                                t.$refs.uToast.show({
                                                    title: `第${[...new Set(t.exceeded_list)].join(',')}张图片超出限制${t.upload_max}MB,已过滤`,
                                                    type: 'warning'
                                                })
                                            }
                                        }
                                    },
                                    fail: (err) => {
                                        t.$refs.uToast.show({
                                            title: '已取消',
                                            type: 'error'
                                        })
                                    }
                                });
                            }
                        }
                    })
                } else {
                    switch (this.types) {
                        case 'image':
                            uni.chooseImage({
                                count: this.uploadCount - this.uploads.length, //默认9
                                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                                sourceType: ['album', 'camera'], //从相册选择
                                success: (res) => {
                                    const tempFilePaths = res.tempFilePaths;
                                    for (let i = 0; i < res.tempFiles.length; i++) {
                                        if (Math.ceil(res.tempFiles[i].size / 1024) < this.upload_max * 1024) {
                                            uni.uploadFile({
                                                url: t.$cfg.uploadurl, //仅为示例，非真实的接口地址
                                                filePath: tempFilePaths[i],
                                                name: 'file',
                                                formData: {
                                                    folderName: t.$cfg.user().userNum
                                                },
                                                success: (uploadFileRes) => {
                                                    var obj = {
                                                        name: JSON.parse(uploadFileRes.data).result.fileName,
                                                        url: JSON.parse(uploadFileRes.data).result.fileDownloadUri,
                                                    }
                                                    this.uploads.push(obj)
                                                    this.uploadImages.push(obj)
                                                    // this.uploads.push(JSON.parse(uploadFileRes.data).result.fileDownloadUri)
                                                    // this.uploadImages.push(JSON.parse(uploadFileRes.data).result.fileDownloadUri)
                                                    this.$emit('successImage', obj)


                                                }
                                            });
                                        } else {
                                            this.exceeded_list.push(i === 0 ? 1 : i + 1);
                                            this.$refs.uToast.show({
                                                title: `第${[...new Set(this.exceeded_list)].join(',')}张图片超出限制${this.upload_max}MB,已过滤`,
                                                type: 'warning'
                                            })
                                        }
                                    }
                                },
                                fail: (err) => {
                                    t.$refs.uToast.show({
                                        title: '已取消',
                                        type: 'error'
                                    })
                                }
                            });
                            break;
                        case 'video':
                            uni.chooseVideo({
                                sourceType: ['camera', 'album'],
                                success: (res) => {
                                    if (Math.ceil(res.size / 1024) < this.upload_max * 1024) {
                                        this.uploads.push(res.tempFilePath)
                                        uni.uploadFile({
                                            url: t.$cfg.uploadurl, //仅为示例，非真实的接口地址
                                            filePath: res.tempFilePath,
                                            name: 'file',
                                            //请求参数
                                            formData: {
                                                folderName: t.$cfg.user().userNum
                                            },
                                            success: (uploadFileRes) => {
                                                console.log(uploadFileRes);
                                                this.$emit('successVideo', uploadFileRes)
                                            }
                                        });
                                    } else {
                                        uni.showModal({
                                            title: '提示',
                                            content: `第${[...new Set(this.exceeded_list)].join(',')}张视频超出限制${this.upload_max}MB,已过滤`
                                        });
                                    }
                                },
                                fail: (err) => {
                                    t.$refs.uToast.show({
                                        title: '已取消',
                                        type: 'error'
                                    })
                                }
                            });
                            break;
                    }
                }

            },
            delImage(index) {
                //第一个是判断app或者h5的 第二个是判断小程序的
                this.uploads.splice(index, 1)
                this.uploadImages.splice(index, 1)
                this.$emit('delImage', index)
                if (this.uploads.length == 0) {
                    this.uploads = true
                }
            },
            upload() {
                if (!t.$cfg.uploadurl) {
                    uni.showModal({
                        content: '请填写上传接口'
                    });
                    return;
                };
                for (let i of this.uploadImages) {
                    uni.uploadFile({
                        url: t.$cfg.uploadurl, //仅为示例，非真实的接口地址
                        filePath: i,
                        name: 'file',
                        //请求参数
                        formData: {
                            'user': 'test'
                        },
                        success: (uploadFileRes) => {
                            this.$emit('successImage', uploadFileRes)
                        }
                    });
                }
            }
        }
    }
</script>

<style scoped>
    .img-wrap {
        width: 100%;
        font-size: 28rpx;
        line-height: 44rpx;
        color: #999999;
        margin: 20rpx 0;
    }

    .add-img {
        display: flex;
        justify-content: center;
        align-items: center;
        border: 4rpx dashed #999;
        font-size: 40rpx;
    }

    .upload {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
    }

    .uplode-file {
        margin: 10upx;
        width: 210upx;
        height: 210upx;
        position: relative;
    }

    .uploade-img {
        display: block;
        width: 210upx;
        height: 210upx;
    }

    .clear-one {
        position: absolute;
        top: -10rpx;
        right: 0;
    }

    .clear-one-icon {
        position: absolute;
        width: 20px;
        height: 20px;
        top: 0;
        right: 0;
        z-index: 9;
    }

    .uploader-input-box {
        position: relative;
        margin: 10upx;
        width: 208upx;
        height: 208upx;
        border: 2upx solid #D9D9D9;
    }

    .uploader-input-box:before,
    .uploader-input-box:after {
        content: " ";
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        background-color: #D9D9D9;
    }

    .uploader-input-box:before {
        width: 4upx;
        height: 79upx;
    }

    .uploader-input-box:after {
        width: 79upx;
        height: 4upx;
    }

    .uploader-input-box:active {
        border-color: #999999;
    }

    .uploader-input-box:active:before,
    .uploader-input-box:active:after {
        background-color: #999999;
    }

    .uploader-input {
        position: absolute;
        z-index: 1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
    }

    .uploader-icon {
        position: relative;
        margin: 10upx;
        width: 208upx;
        height: 208upx;
    }

    .uploader-icon .image-cion {
        width: 100%;
        height: 100%;
    }
</style>